package com.paco.study.cloud.gateway.filter;

import com.paco.study.cloud.gateway.feign.UserFeignClient;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.ForwardRoutingFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.reactive.DispatcherHandler;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 校验cookie，如果已登录，跳转到login页面
 */
@Component
public class AuthFilter extends ForwardRoutingFilter implements Ordered {

    @Autowired
    private UserFeignClient userFeignClient;

    private static final Set<String> WHITE_URLS = new HashSet<String>();

    static {
        WHITE_URLS.add("/api/user/");
        WHITE_URLS.add("/api/code/");
    }

    public AuthFilter(ObjectProvider<DispatcherHandler> dispatcherHandler) {
        super(dispatcherHandler);
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

//        是否白名单
        String uri = request.getPath().toString();
        boolean isWhite = WHITE_URLS.stream()
                .anyMatch(uri::startsWith);

        if (!isWhite) {
//        获取token
            MultiValueMap<String, HttpCookie> cookies = request.getCookies();
            List<HttpCookie> sessionCookies = cookies.get("mySession");

            String email = null;
            if (sessionCookies != null) {
                String token = sessionCookies.stream()
                        .filter(se -> "mySession".equals(se.getName())).findFirst()
                        .map(HttpCookie::getValue)
                        .orElse(null);

//                token是否合法
                if (!StringUtils.isEmpty(token)) {
                    email = userFeignClient.info(token);
                }
            }

            //跳转到login.html
            if (StringUtils.isEmpty(email)) {
                String url = "/login.html";
                response.setStatusCode(HttpStatus.SEE_OTHER);
                response.getHeaders().set(HttpHeaders.LOCATION, url);
                return response.setComplete();
            }
        }

        return chain.filter(exchange);
    }


    /**
     * 返回值表示当前过滤器的顺序(优先级)，数值越小，优先级越高
     *
     * @return
     */
    @Override
    public int getOrder() {
        return 1;
    }
}
